package com.hailong.zyt.controller;


import com.hailong.zyt.beans.Admin;
import com.hailong.zyt.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PutMapping;

import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hailong
 * @since 2021-05-13
 */
@Slf4j
@Controller
public class AdminController {

    private AdminService adminService;
    @Autowired
    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

    /**
    * 管理员登录
    * */
    @GetMapping("/index/adminLogin")
    public String toAdminLogin() {
        return "/index/adminLogin";
    }

    @PostMapping("/index/adminLogin")
    public String adminLogin(Admin user, HttpSession session) {
        Admin admin = adminService.login(user);
        log.info("管理员：{}", user);
        if(admin != null) {
            log.info("管理员：{}", "登录成功");
            session.setAttribute("admin", admin);
            session.setAttribute("userType", "admin");
            return "redirect:/admin/main";
        }
        else {
            return "/index/adminLogin";
        }
    }

    /**
     * 退出登录
     * */
    @GetMapping("/admin/loginOut")
    public String loginOut(HttpSession session) {
        session.removeAttribute("admin");
        return "redirect:/";
    }

    /**
    * 首页
    * */
    @GetMapping("/admin/main")
    public String toMain(){
        return "/admin/admMain";
    }


    /**
    * 修改信息
    * */
    @GetMapping("/admin/info")
    public String toInfo(HttpSession session, Model model){
        Admin user = (Admin) session.getAttribute("admin");
        model.addAttribute("admin", user);
        return "/admin/admInfo";
    }

    @PutMapping("/admin/updateInfo")
    public String updateInfo(Admin newAdmin){
        adminService.saveOrUpdate(newAdmin);
        return "redirect:/admin/info";
    }
    @PutMapping("/admin/changePassword")
    public String changePassword(Admin newAdmin, String newPassword, String reNewPassword, Model model, HttpSession session){
        if(!reNewPassword.equals(newPassword)){
            model.addAttribute("msg", "两次密码不一致");
            return "/admin/admInfo";
        }
        newAdmin.setAdmPassword(newPassword);
        adminService.saveOrUpdate(newAdmin);
        session.setAttribute("admin", adminService.getById(newAdmin.getAdmId()));
        return "redirect:/admin/info";
    }
}

